<?php

namespace app\models;

use Yii;
use yii\base\Exception;
use yii\db\ActiveRecord;

/**
 * 用户卡充值
 * Class UserCardRecharge
 * @package app\models
 *
 * @property integer $id PK
 * @property integer $uid 用户编号
 * @property integer $agent_id 代理商编号
 * @property integer $card_id 卡编号
 * @property integer $package_id 套餐编号
 * @property integer $term_length 套餐有效期
 * @property integer $term_length_unit 套餐有效期单位
 * @property float $price 价格
 * @property float $money 金额
 * @property integer $trade_type 支付方式
 * @property string $trade_no 平台交易流水号
 * @property string $trans_id 第三方交易支付流水号
 * @property integer $status 状态
 * @property integer $create_time 创建时间
 * @property integer $pay_time 支付时间
 * @property integer $update_time 卡更新时间
 * @property string $input 第三方支付输入
 * @property string $output 第三方支付输出
 * @property string $notify 第三方支付回调
 * @property string $remark 备注
 *
 * @property User $user 关联用户
 * @property Agent $agent 关联代理商
 * @property Card $card 关联卡
 * @property Package $package 关联套餐
 */
class UserCardRecharge extends ActiveRecord
{
    const TERM_LENGTH_UNIT_MINUTE = Card::TERM_LENGTH_UNIT_MINUTE; // 套餐有效期单位分钟
    const TERM_LENGTH_UNIT_DAY = Card::TERM_LENGTH_UNIT_DAY; // 套餐有效期单位天
    const TERM_LENGTH_UNIT_MONTH = Card::TERM_LENGTH_UNIT_MONTH; // 套餐有效期单位月

    const TRADE_TYPE_WX_JSAPI = 1;

    const STATUS_WAIT_PAY = 1;
    const STATUS_PAID = 2;
    const STATUS_RECHARGE = 3;
    const STATUS_DELETE = 0;

    /**
     * 关联用户
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::class, ['id' => 'uid']);
    }

    /**
     * 关联代理商
     * @return \yii\db\ActiveQuery
     */
    public function getAgent()
    {
        return $this->hasOne(Agent::class, ['id' => 'agent_id']);
    }

    /**
     * 关联卡
     * @return \yii\db\ActiveQuery
     */
    public function getCard()
    {
        return $this->hasOne(Card::class, ['id' => 'card_id']);
    }

    /**
     * 关联套餐
     * @return \yii\db\ActiveQuery
     */
    public function getPackage()
    {
        return $this->hasOne(Package::class, ['id' => 'package_id']);
    }
    //关联代理套餐
    public function getPackages(){
        return $this->hasOne(AgentPackage::class,['package_id' => 'package_id','agent_id'=>'agent_id']);
    }
    /**
     * 设置已支付
     * @throws Exception
     */
    public function setPaid()
    {
        $this->updateAttributes(['status' => UserCardRecharge::STATUS_RECHARGE, 'pay_time' => time()]);
        $dgcs = Card::findOne(['id'=>$this->card_id])->getAttribute('dgcs');
        $is_reward = Card::findOne(['id'=>$this->card_id])->getAttribute('is_reward');
        if ($this->term_length_unit != Card::TERM_LENGTH_UNIT_MONTH) {
            Yii::warning('卡充值【' . $this->id . '】计算代理商利润目前只支持按月为单位充值的情况。');
        } else {
            if (!empty($this->agent_id)) {
				$commagent = AgentConfig::getConfig($this->agent_id, 'comm_agent');
				if ($commagent == 2) {
					$comm_type = 1;
				} else {
					$comm_type = 0;
				}	//代理商返佣类型为上级返佣，返佣记录也为上级返佣
                $agentPackage = AgentPackage::findOne(['agent_id' => $this->agent_id, 'package_id' => $this->package_id]);
                $agentProfit = $this->money - $agentPackage->cost_price; // 代理商利润
				//$agentProfit = $this->money - $agentPackage->cost_price; // 代理商利润
                $this->saveAgentProfit($this->agent_id,$this->package_id,$agentProfit,$dgcs,$agentPackage->active_reward,$is_reward,$comm_type);
                
                $parent = $this->agent;
                while (!empty($parent->pid)) {
                    $current = $parent;
                    $parent = $parent->parent;
                    $currentAgentPackage = AgentPackage::findOne(['agent_id' => $current->id, 'package_id' => $this->package_id]);
                    $parentAgentPackage = AgentPackage::findOne(['agent_id' => $parent->id, 'package_id' => $this->package_id]);
                    if (empty($currentAgentPackage) || empty($parentAgentPackage)) {
                        break;
                    }
					$parentcommagent = AgentConfig::getConfig($parent->id, 'comm_agent');
					if ($parentcommagent == 2) {
						$comm_type = 1;
					} else {
						$comm_type = 0;
					}	//代理商返佣类型为上级返佣，返佣记录也为上级返佣
					if ($parentcommagent == 1) {
						$parentProfit = $this->money - $parentAgentPackage->cost_price;
					} else {
						$parentProfit = $currentAgentPackage->cost_price - $parentAgentPackage->cost_price;
					} //代理商返佣类型为1全额，则将全部佣金给代理商，否则按原规则递减。
					//$parentProfit = $currentAgentPackage->cost_price - $parentAgentPackage->cost_price;
                    $active_reward = 0;
                    $this->saveAgentProfit($parent->id,$this->package_id,$parentProfit,$dgcs,$active_reward,$is_reward,$comm_type);
                    
                }
            }
        }
    }
    
    
    /**
     * 记录代理商收益
     * @param integer $agentId 代理商编号
     * @param float $money 收益金额
     * @return bool
     * @throws Exception
     */
    private function saveAgentProfit($agentId,$packageId,$money,$dgcs,$active_reward,$is_reward,$comm_type)
    {
        //订购次数为1时的代理激活奖励
        if($dgcs == '1' && $is_reward == '0'){
                $profit = new AgentProfit();
                $profit->agent_id = $agentId;
                $profit->package_id = $packageId;
                $profit->user_card_recharge_id = $this->id;
                $profit->source = $this->source;
                //判断是否有激活奖励
                if($active_reward == '0'){
                    $profit->money = $money;
                    $profit->profit_type = '1';
                }else{
                    $profit->money = $active_reward;
                    $profit->profit_type = '2';
                }
                $profit->card_id = $this->card_id;
                $profit->create_time = time();
                $day = date('Y-m-d',time());
                $today = strtotime($day);
                $profit->same_time = $today;
    			$profit->comm_type = $comm_type;
                $profit->save();
                if($active_reward > 0){
                   Yii::$app->db->createCommand()->update('card', ['is_reward' => 1], 'id = :id',['id' => $this->card_id])->execute();  
                }
        }else{
            //佣金大于0才写入表
            if($money > 0){
                $profit = new AgentProfit();
                $profit->agent_id = $agentId;
                $profit->package_id = $packageId;
                $profit->user_card_recharge_id = $this->id;
                $profit->source = $this->source;
                $profit->card_id = $this->card_id;
                $profit->money = $money;
                $profit->create_time = time();
                $day = date('Y-m-d',time());
                $today = strtotime($day);
                $profit->same_time = $today;
                $profit->comm_type = $comm_type;
                $profit->save();
            }
            
        }
        
        // if (!$profit->save()) {
        //     throw new Exception('无法保存收益记录。');
        // }

        $log = new AgentAccountLog();
        $log->agent_id = $agentId;
        $log->money = $money;
        $log->create_time = time();
        $log->remark = '用户卡充值利润';
        if (!$log->save()) {
            throw new Exception('无法保存账户记录。');
        }

        // if (AgentAccount::updateAllCounters(['money' => $money], ['agent_id' => $agentId]) <= 0) {
        //     throw new Exception('无法更新账户。');
        // }

        return true;
    }

    //转换流量从B到G
    public function formatUsage($data){
        $result = round($data/1024/1024/1024,2);
        return $result;
    }
}
